﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace RVBike
{
    /// <summary>
    /// Interaction logic for SinglePlayerPage.xaml
    /// </summary>
    public partial class SinglePlayerPage : UserControl, ISwitchable
    {
        private int _stageIndex;
        private RVStage _currentStage;
        private int _currentPage;
        private GameMode _currentMode;
        private string _roomName;
		private bool _multiPlayer;

        public SinglePlayerPage(bool multi)
        {
            InitializeComponent();

            _stageIndex = -1;
            _currentStage = null;
            _currentPage = 0;
			_multiPlayer = multi;
            _roomName = "New Room";

            // Multi-language string
            btn_start.Content = MultiLanguage.Instance().Translate("start");
            btn_load.Content = MultiLanguage.Instance().Translate("load");
            btn_back.Content = MultiLanguage.Instance().Translate("back");
            Dummy_roomName.Content = MultiLanguage.Instance().Translate("room_name");
            Dummy_netType.Content = MultiLanguage.Instance().Translate("network_type");
            Dummy_gameMode.Content = MultiLanguage.Instance().Translate("game_mode");
            GameModeNormal.Content = MultiLanguage.Instance().Translate("normal_mode_start");
            Dummy_gameSpeed.Content = MultiLanguage.Instance().Translate("game_speed");
            GameModeMileage.Content = MultiLanguage.Instance().Translate("mileage_mode");
            GameModeTime.Content = MultiLanguage.Instance().Translate("time_mode");
            Dummy_hr.Content = MultiLanguage.Instance().Translate("time_mode_hour");
            Dummy_min.Content = MultiLanguage.Instance().Translate("time_mode_minute");
            Dummy_sec.Content = MultiLanguage.Instance().Translate("time_mode_second");
        }
		
        #region ISwitchable Members
        public void UtilizeState(object state)
        {
            throw new NotImplementedException();
        }

        public void WindowLocationChanged(double x, double y)
        {
        }
        #endregion

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (StageManager.Instance().StageCount > 0)
            {
                _stageIndex = 0;
            }
            UpdatePage();
        }

        private void UpdatePage()
        {
            // Disable all contorls
            if (_stageIndex == -1)
            {
                this.IsEnabled = false;
                return;
            }

            stageTitle.Content = String.Format(MultiLanguage.Instance().Translate("choose_favorite_map"), _currentPage + 1, (int)(StageManager.Instance().StageCount / 6 + 1));
            UpdateStage();

            for (int i = 0; i < 6; i++)
            {
                int t_pageNum = _currentPage * 6 + i;
                if (t_pageNum > (StageManager.Instance().StageCount - 1))
                    break;
                RVStage t_stage = StageManager.Instance().GetStage(t_pageNum);
                
                switch(i)
                {
                    case 0:
                        mapImage.Source = new BitmapImage(new Uri(t_stage.CoverPath));
                        mapName.Content = t_stage.DisplayName;
                        break;
                    case 1:
                        mapImage1.Source = new BitmapImage(new Uri(t_stage.CoverPath));
                        mapName1.Content = t_stage.DisplayName;
                        break;
                    case 2:
                        mapImage2.Source = new BitmapImage(new Uri(t_stage.CoverPath));
                        mapName2.Content = t_stage.DisplayName;
                        break;
                    case 3:
                        mapImage3.Source = new BitmapImage(new Uri(t_stage.CoverPath));
                        mapName3.Content = t_stage.DisplayName;
                        break;
                    case 4:
                        mapImage4.Source = new BitmapImage(new Uri(t_stage.CoverPath));
                        mapName4.Content = t_stage.DisplayName;
                        break;
                    case 5:
                        mapImage5.Source = new BitmapImage(new Uri(t_stage.CoverPath));
                        mapName5.Content = t_stage.DisplayName;
                        break;
                }
            }
			
			if(_multiPlayer)
			{
				Cbox_netType.Items.Add(MultiLanguage.Instance().Translate("lan_game"));
                Cbox_netType.Items.Add(MultiLanguage.Instance().Translate("internet_game"));
				panel_network.IsEnabled = true;

                // Multiplayer game cannot change speed!
                panel_gameSpeed.IsEnabled = false;
                panel_gameSpeed.Visibility = Visibility.Collapsed;

                // Multiplayer game cannot load saved state
                btn_load.IsEnabled = false;
			}
			else
			{
				Tbox_roomName.Text = "Room 1";
				panel_roomName.IsEnabled = false;
                panel_roomName.Visibility = Visibility.Collapsed;
				
				Cbox_netType.Items.Add("Single Game");
				panel_network.IsEnabled = false;
                panel_network.Visibility = Visibility.Collapsed;
			}

            txt_user_name.Text = UserSetting.Instance().UserName;
            txt_info.Text = _currentStage.Description;
        }

        private void UpdateStage()
        {
            _currentStage = StageManager.Instance().GetStage(_stageIndex);
            
            Color t_red = (Color)ColorConverter.ConvertFromString("#FFFF0000");
            Color t_black = (Color)ColorConverter.ConvertFromString("#FF000000");

            // Init the Name Color
            {
                mapName.Foreground = new SolidColorBrush(t_black);
                mapName1.Foreground = new SolidColorBrush(t_black);
                mapName2.Foreground = new SolidColorBrush(t_black);
                mapName3.Foreground = new SolidColorBrush(t_black);
                mapName4.Foreground = new SolidColorBrush(t_black);
                mapName5.Foreground = new SolidColorBrush(t_black);
            }
            
            switch (_stageIndex%6)
            {
                case 0:
                    mapName.Foreground = new SolidColorBrush(t_red);
                    break;
                case 1:
                    mapName1.Foreground = new SolidColorBrush(t_red);
                    break;
                case 2:
                    mapName2.Foreground = new SolidColorBrush(t_red);
                    break;
                case 3:
                    mapName3.Foreground = new SolidColorBrush(t_red);
                    break;
                case 4:
                    mapName4.Foreground = new SolidColorBrush(t_red);
                    break;
                case 5:
                    mapName5.Foreground = new SolidColorBrush(t_red);
                    break;
            }

            Tbox_roomName.Text = _roomName;
            txt_info.Text = _currentStage.Description;

            // Update mileage range
            Label_mile_range.Content = String.Format(MultiLanguage.Instance().Translate("mileage_mode_range"), _currentStage.Mileage);
        }

		private void OnButtonClick(object sender, RoutedEventArgs e)
        {
            if (sender == btn_back)
            {
				if (_multiPlayer)
					RVSwitcher.Switch(new MultiplePlayerPage());
				else	
					RVSwitcher.Switch(new MainPage());
            }
            else if (sender == btn_load)
            {
                LoadGameWindow loadGame = new LoadGameWindow();
                loadGame.Left = Application.Current.MainWindow.Left + Application.Current.MainWindow.Width / 2 -
                    loadGame.Width / 2;
                loadGame.Top = Application.Current.MainWindow.Top + Application.Current.MainWindow.Height / 2 -
                    loadGame.Height / 2;

                if (loadGame.ShowDialog().Value)
                {
                    RVSwitcher.Switch(new MainGamePage(),
                        new GameSetting
                        {
                            GameType = GameType.Single,
                            GameMode = _currentMode,
                            SelectedStage = _currentStage,
                            RoomName = "",
                            GameSpeed = sld_gameSpeed.Value
                        });
                }
            }
            else if (sender == btn_start)
            {
                if (_multiPlayer)
                {
                    // Create server before switch page
                    string roomName = _roomName;
                    string gameMode = RVNetworkEnv.GAME_MODE_NORMAL;
                    string mcastIP = "239.0.0.1"; // [FIXME] hardcode now!!!
                    string userName = "User1"; // [FIXME] hardcode now!!!

                    switch (_currentMode)
                    {
                        case GameMode.Normal: gameMode = RVNetworkEnv.GAME_MODE_NORMAL; break;
                        case GameMode.Mileage: gameMode = RVNetworkEnv.GAME_MODE_MILEAGE; break;
                        case GameMode.Time: gameMode = RVNetworkEnv.GAME_MODE_TIME; break;
                    }

                    Dictionary<string, string> info = new Dictionary<string, string>();
                    info.Add(RVBike.RVNetworkEnv.ROOM_NAME, roomName);
                    info.Add(RVBike.RVNetworkEnv.MAP_NAME, _currentStage.Name);
                    info.Add(RVBike.RVNetworkEnv.GAME_MODE, gameMode);
                    info.Add(RVBike.RVNetworkEnv.CURRENT_USER_COUNT, "" + 0);
                    info.Add(RVBike.RVNetworkEnv.MAX_USER_COUNT, "" + 5);
                    info.Add(RVBike.RVNetworkEnv.SERVER_IP, RVBike.NetworkUtility.MyIP());
                    info.Add(RVBike.RVNetworkEnv.MCAST_IP, mcastIP);
                    info.Add(RVBike.RVNetworkEnv.ROOM_STATE, RVNetworkEnv.ROOM_STATE_OPEN);

                    // Create room
                    RVRoom room = new RVRoom(info);
                    RVGameController.Instance().CreateRoom(room, userName, mcastIP);

                    RVSwitcher.Switch(new RoomPage(),
                                    new GameSetting
                                    {
                                        GameType = GameType.Lan,
                                        GameMode = _currentMode,
                                        SelectedStage = _currentStage,
                                        RoomName = _roomName,
                                        GameSpeed = 1.0
                                    });
                }
                else
                {
                    RVSwitcher.Switch(new MainGamePage(),
                                    new GameSetting
                                    {
                                        GameType = GameType.Single,
                                        GameMode = _currentMode,
                                        SelectedStage = _currentStage,
                                        RoomName = "",
                                        GameSpeed = sld_gameSpeed.Value
                                    });
                }
            }
            else if (sender == btn_left)
            {
                if (--_currentPage < 0)
                {
                    _currentPage = (int)(StageManager.Instance().StageCount / 6);
                    _stageIndex = _currentPage * 6;
                }
                UpdatePage();
            }
            else if (sender == btn_right)
            {
                if (++_currentPage > (int)(StageManager.Instance().StageCount / 6))
                {
                    _currentPage = 0;
                    _stageIndex = 0;
                }
                UpdatePage();
            }
        }

        private void OnModeChanged(object sender, RoutedEventArgs e)
        {
            if (sender == GameModeNormal) _currentMode = GameMode.Normal;
            else if (sender == GameModeMileage) _currentMode = GameMode.Mileage;
            else if (sender == GameModeTime) _currentMode = GameMode.Time;
            else new ArgumentException();
        }

        private void OnMapClick(object sender, MouseButtonEventArgs e)
        {
            int selected = -1;
            if (sender == mapImage) selected = 0;
            else if (sender == mapImage1) selected = 1;
            else if (sender == mapImage2) selected = 2;
            else if (sender == mapImage3) selected = 3;
            else if (sender == mapImage4) selected = 4;
            else if (sender == mapImage5) selected = 5;

            if (selected >= 0)
            {
                _stageIndex = (_currentPage * 6) + selected;
                UpdateStage();
            }
        }

        private void Tbox_roomName_TextChanged(object sender, TextChangedEventArgs e)
        {
            _roomName = Tbox_roomName.Text;
        }
    }
}
